#include <Arduino.h>
#include <ESP8266WiFi.h>
#include "postdata.h"
#include "mysql_aliyun.h"
#define URL_time "http://quan.suning.com/getSysTime.do"
#define URL_tianqi "http://api.jirengu.com/getWeather.php?city=淄博"

IPAddress server(183,230,40,39);        // OneNet的服务器地址
WiFiClient wifiClient;               // 声明一个WiFiClient对象，用来初始化 MQTT对象

void callback(char *topic, byte *payload, unsigned int length);
PubSubClient MQTTClient(server, 6002, callback, wifiClient);                // 声明一个MQTT对象


/* OneNet自己定义设备的信息 */
#define PRODUCT_ID "364314"
#define API_KEY "o4qzEqGG0nmMmS2EjLnjI=7sizM="
#define DEVICE_ID "615012994"
#define TOPIC "esp8266led"

const char *ssid     = "鑫青年";           // wifi的ssid
const char *passw = "guoxin0814..";      // wifi密码


void setup(void)
{
    // 串口波特率
    Serial.begin(9600);
    Serial.println();
    Serial.printf("Wifi Connecting to %s\n", ssid);

    WiFi.mode(WIFI_STA);                            // 默认情况下，ESP8266将尝试充当客户端和接入点。为避免干扰现有WIFI网络，明确将其设置为WiFi客户端。
    WiFi.begin(ssid, passw);                     // 启动Wifi连接


    while (WiFi.status() != WL_CONNECTED)           // 阻塞式等待，直到连接成功
    {
        delay(500);                                 // 每500MS检测一次，一直到连接成功
        Serial.print(".");
    }

    Serial.println();
    Serial.print("WiFi Connected OK, IP address: ");  // 显示WIFI连接成功获取的本地IP
    // 192,168,0,22
    Serial.println(WiFi.localIP());
    
    if(Mysql_judge_connect()){
      Serial.println("数据库连接成功");
    }
    else{
      Serial.println("数据库连接失败");
    }
    
    pinMode(16, OUTPUT);
    digitalWrite(16, LOW);
    pinMode(0, OUTPUT);
    digitalWrite(0, LOW);
    pinMode(15, OUTPUT);
    digitalWrite(15, LOW);
}

void loop()
{
    
    HTTPClient_POST("30");
    if (!MQTTClient.connected()) {
        reconnect(PRODUCT_ID, API_KEY, DEVICE_ID);
    }
    MQTTClient.loop();
    //read_times("1");
    //read_tianqi("2");
    read_t(URL_time);
    read_t(URL_tianqi);
    xianshi("3");
}
// 回调函数，用来打印出信息的主题、返回信息和长度
void callback(char* topic, byte* payload, unsigned int length) {
    Serial.print("Message arrived [");
    Serial.print(topic);
    Serial.print("] ");
    for (int i=0; i<length; i++) {
        Serial.print((char)payload[i]);
    }
    Serial.println();

    if ((char)payload[0] == '1') {
        digitalWrite(16, HIGH);
        delay(5000);
    }else if((char)payload[0] == '2'){
        digitalWrite(16, LOW);
        delay(5000);
    }else if((char)payload[0] == '3'){
        digitalWrite(0, HIGH);
        delay(5000);
    }else if((char)payload[0] == '4'){
        digitalWrite(0, LOW);
        delay(5000);
    }else if((char)payload[0] == '5'){
        digitalWrite(15, HIGH);
        delay(5000);
    }else if((char)payload[0] == '6'){
        digitalWrite(15, LOW);
        delay(5000);
    }
}
// 重连接
void reconnect(char *onenet_productId, char *onenet_apiKey, char *onenet_deviceId) {
    
    while (!MQTTClient.connected()) {
        Serial.print("Attempting MQTT connection...");
        // Attempt to connect
        if (MQTTClient.connect(onenet_deviceId,onenet_productId,onenet_apiKey)) {
            Serial.println("connected");
            // Once connected, publish an announcement...
            MQTTClient.publish("outTopic","hello world");
            // ... and resubscribe
            MQTTClient.subscribe(TOPIC, 1);
        } else {
            Serial.print("failed, rc=");
            Serial.print(MQTTClient.state());
            Serial.println(" try again in 5 seconds");
            // Wait 5 seconds before retrying
            delay(1000);
        }
    }
}
